package javaExercise;

/**
 * @author Cyxan
 * @version 1.0
 */
public class OddEventPrinter1 {

    private static final Object lock = new Object();
    private static volatile int number = 1;
    private static final int MAX = 100;
    public static void main(String[] args) {

        Thread oddThread = new Thread(() -> {
            while (number <= MAX){
                synchronized (lock){
                    if (number % 2 == 0){
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }else {
                        System.out.println("奇数线程: " + Thread.currentThread().getName() + " : " + number);
                        number++;
                        lock.notify();
                    }
                }
            }
        }, "OddThread");

        Thread evenThread = new Thread(() -> {
            while (number <= MAX){
                synchronized (lock){
                    if (number % 2 != 0){
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }else {
                        System.out.println("偶数线程: " + Thread.currentThread().getName() + " :" + number);
                        number++;
                        lock.notify();
                    }
                }
            }
        }, "EvenThread");

        oddThread.start();
        evenThread.start();
    }
}
